package com.weixing.mall.provider.support.mq;

import com.weixing.mall.provider.service.IActivityGoodsService;
import com.weixing.mall.redis.RedisKeyConst;
import com.weixing.mall.redis.order.OrderDivStock;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Order(2)
public class OrderDivStockRedissionQueueConsumer implements CommandLineRunner {

    private RedissonClient redissonClient;

    @Autowired
    private IActivityGoodsService activityGoodsService;

    @Resource
    private TaskExecutor taskExecutor;

    @Autowired
    public OrderDivStockRedissionQueueConsumer(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    private void  consumer(){
        RBlockingQueue<OrderDivStock> blockingFairQueue = redissonClient.getBlockingQueue(RedisKeyConst.QUEUE_ORDER_DIV_STOCK);
        while (true) {
            OrderDivStock payEnd = null;
            try {
                payEnd = blockingFairQueue.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            System.out.println("活动订单扣减库存：" + payEnd.getOrderId() + "::" + payEnd.getItemId() + "::" + payEnd.getActId());
//            activityGoodsService.offLoading(payEnd.getActId(),  payEnd.getItemId());
            activityGoodsService.divideStock(payEnd.getActId(), payEnd.getItemId(), payEnd.getCnt());
        }
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("启动第二个任务");
        taskExecutor.execute(() -> this.consumer());
    }
}